package com.czl.myRabbitMq.mqServer.dataCenter;

import com.czl.myRabbitMq.MyRabbitMqApplication;
import com.czl.myRabbitMq.mqServer.core.Binding;
import com.czl.myRabbitMq.mqServer.core.Exchange;
import com.czl.myRabbitMq.mqServer.core.ExchangeType;
import com.czl.myRabbitMq.mqServer.core.MSGQueue;
import com.czl.myRabbitMq.mqServer.mapper.ExchangeMapper;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.util.List;

@Slf4j
public class DataManager {
    /**
     * @Autowired注解使用的前提是该类也被spring容器管理
     * 本项目改类不被spring容器管理的前提下我们需要自己手动创建exchangeMapper类
     */

    private ExchangeMapper exchangeMapper;

    /**
     *该方法为执行项目时的初始化方法
     * 要是在执行过程中存在相应的表则不进行操作
     * 要是不存在相应的表则进行创建表的操作
     */
    public void init(){
        exchangeMapper = MyRabbitMqApplication.context.getBean(ExchangeMapper.class);
        //创建默认数据库的目录
        File file = new File("./data");
        file.mkdirs();
        if(!isExitMeta()){
            //创建默认数据库
            createTable();
            //插入默认数据
            insertInitData();
            log.info("初始化建表成功");
        }
    }
    public void insertExchange(Exchange exchange){
        exchangeMapper.insertExchange(exchange);
    }

    public void deleteExchange(String ExchangeName){
        exchangeMapper.deleteExchange(ExchangeName);
    }

    public List<Exchange> selectAllExchange(){
        return exchangeMapper.selectAllExchange();
    }

    public void insertQueue(MSGQueue queue){
        exchangeMapper.insertQueue(queue);
    }

    public void deleteQueue(String queueName){
        exchangeMapper.deleteQueue(queueName);
    }
    public List<MSGQueue> selectAllQueue(){
        return exchangeMapper.selectAllQueue();
    }
    public void insertBinding(Binding binding){
        exchangeMapper.insertBinding(binding);
    }
    public void deleteBinding(String exchangeName, String queueName){
        exchangeMapper.deleteBinding(exchangeName, queueName);
    }
    public List<Binding> selectAllBinding(){
        return exchangeMapper.selectAllBinding();
    }
    private boolean isExitMeta(){
        File file = new File("./data/meta.db");

        if(file.exists())
            return true;

        return false;
    }


    private void createTable(){
        exchangeMapper.createExchange();
        exchangeMapper.createBinding();
        exchangeMapper.createQueue();
    }
    private void insertInitData(){
        Exchange exchange = new Exchange();
        exchange.setExchangeType(ExchangeType.DIRECT);
        exchange.setName("");
        exchange.setDurable(true);
        exchange.setAutoDelete(false);
        exchangeMapper.insertExchange(exchange);
    }
}
